package com.sh.data.engine.application.service.api;

import com.sh.data.engine.application.model.dto.api.DataApiCallResponse;
import com.sh.data.engine.common.util.AESUtil;
import com.sh.data.engine.common.util.RSAUtil;
import com.sh.data.engine.common.util.ServletUtils;
import com.sh.data.engine.domain.api.run.DataApiConfig;
import com.sh.data.engine.domain.api.service.DataApiService;
import com.sh.data.engine.domain.base.model.UserContext;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.URLDecoder;

/**
 * @author: mengzheng.mhc
 * @date: 2024/8/15 17:42
 */
@Slf4j
@Service
public class DataApiCallApplicationService {

    private static final String SERVLETPATH = "/restData";

    @Autowired
    private DataApiService dataApiService;

    @Autowired
    private DataApiConfig dataApiConfig;

    public DataApiCallResponse getDemoUrlDetail() {
        StringBuilder sb = new StringBuilder();

        String dataApiUriPrefix = dataApiConfig.getDataApiUriPrefix();
        if (StringUtils.isNotBlank(dataApiUriPrefix)) {
            sb.append(dataApiUriPrefix);
            if (dataApiUriPrefix.endsWith("/")) {
                sb.deleteCharAt(sb.length() - 1);
            }
        }
        String contextPath = ServletUtils.getRequest().getContextPath();
        if (!StringUtils.contains(dataApiUriPrefix, contextPath)) {
            sb.append(contextPath);
        }
        if (!StringUtils.contains(dataApiUriPrefix, SERVLETPATH)) {
            sb.append(SERVLETPATH);
        }
        String userToken = UserContext.getUserInfo().getUserToken();
        String apiExample = sb.append("/path").toString();
        String apiToken = "8918637ec25244e691657397265a2ca1";
        DataApiCallResponse dataApiCallResponse = new DataApiCallResponse();
        dataApiCallResponse.setApiExample(apiExample);
        dataApiCallResponse.setApiToken(apiToken);
        dataApiCallResponse.setUserToken(userToken);
        return dataApiCallResponse;
    }

    @SneakyThrows
    public boolean resetUserToken(String password) {
        // TODO: remove password
        String plaintextValue = RSAUtil.decryptByPrivateKey(password, "UTF-8");
        plaintextValue = URLDecoder.decode(plaintextValue, "UTF-8");
        dataApiService.resetUserToken(AESUtil.encrypt(plaintextValue));
        return true;
    }
}
